package cn.edu.zafu.bigdata.x.Foo;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class FileOperations {
    // 将用户输入的文本写入到指定的文件中
    public static void writeToFile(String fileName, String content) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(new File(fileName)))) {
            writer.write(content);
        } catch (IOException e) {
            System.out.println("Error writing to file: " + e.getMessage());
        }
    }

    // 读取文件内容并将其打印到控制台
    public static void readFromFile(String fileName) {
        try {
            // 使用java 8的Files类来简化文件读取
            java.nio.file.Files.lines(java.nio.file.Paths.get(fileName))
                    .forEach(System.out::println);
        } catch (IOException e) {
            System.out.println("Error reading from file: " + e.getMessage());
        }
    }

    // 主方法，用于测试写入和读取文件的功能
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String rootDir = System.getProperty("user.dir");
        System.out.println("程序根目录:" + rootDir);
        System.out.println("Please enter the text you want to save:");
        String text = scanner.nextLine();

        // 文件路径，假设files目录已经存在
        String fileName = rootDir + "/files/202211080117.txt";

        // 将用户输入的文本写入文件
        writeToFile(fileName, text);

        // 读取并显示文件内容
        System.out.println("文本内容如下：");
        readFromFile(fileName);

        scanner.close();
    }
}

